package com.hack4jp.hackearthquakes;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class TwitterAdapter extends ArrayAdapter<TweetItem> {
	
	static public final String DATE_PATTERN ="yyyy-MM-dd HH:mm:ss";
	
	private Context _context;
	private ArrayList<TweetItem> _items;
	private LayoutInflater _inflater;
	
	public TwitterAdapter(Context context, int resourceId, ArrayList<TweetItem> items)
	{
		super(context, resourceId, items);
		this._context = context;
		this._inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this._items = items;
	}
	
	public void addItem(String tweetText, URL imageUrl, Date dt)
	{
		this._items.add(new TweetItem(tweetText, imageUrl, dt));
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		if (convertView == null) {
			convertView = _inflater.inflate(R.layout.tlrow, null);
		}
		
		if (position >= _items.size())
			return convertView;

		TweetItem item = _items.get(position);
		
		TextView txtDate = (TextView)convertView.findViewById(R.id.date_tweet);
		if (txtDate != null) {
			String strDate = (new SimpleDateFormat(DATE_PATTERN)).format(item.getTweetDate());
			txtDate.setText(strDate);
		}
		
		TextView txtTweet = (TextView)convertView.findViewById(R.id.text_tweet);
		if (txtTweet != null) {
			txtTweet.setText(item.getTweetText());
		}
			
		ImageView image = (ImageView)convertView.findViewById(R.id.icon);
		ProgressBar progress = (ProgressBar)convertView.findViewById(R.id.progress);
		if (image != null && progress != null) {
			progress.setVisibility(View.VISIBLE);
			image.setVisibility(View.GONE);
			
			image.setImageDrawable(_context.getResources().getDrawable(R.drawable.icon));
			try{
				URL url = item.getImageUrl();
				String urlString = url.toString();
				image.setTag(urlString);
	            // AsyncTaskは１回しか実行できない為、毎回インスタンスを生成
				DownloadImageTask task = new DownloadImageTask(_context, image, progress);
	            task.execute(urlString);
	        }
	        catch(Exception e){
	            progress.setVisibility(View.GONE);
	            image.setVisibility(View.VISIBLE);
	        }
		}
		
		return convertView;
	}
}
